var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate,purchaseNo=getQueryVariable("purchaseNo");

layui.use(['tableEdit',"excel"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        excel = layui.excel;

    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    function getAllJson(jsons) {
        let tmpitem = []
        for (let item of jsons) {
            let tmparr = {}
            tmparr["value"] = item["code"];
            tmparr["name"] = item["name"];
            if (item["users"]) {
                for (let it of item["users"]) {
                    item["list"].push(it)
                }
            }
            if (item["list"] && item["list"].length) {
                tmparr["children"] = getAllJson(item["list"]);
                tmpitem.push(tmparr)
            } else {
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }
    let operationList=[];
    let salesmanList=[];
    let businessModelList=[];
    let deptSalesmanList = [];
    let deptOperationList=[];
    layer.ready(function () {
        $.ajax({
            //获取供应商信息
            url: "payment/getSupplierInfo",
            success: function (data) {
                if (data.status == 200) {
                    for (let i in data.data) {
                        $('#supplierCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取当前用户的部门及人员结构树
        let treeList = getCurrentDepartmentUser();

        if (treeList && treeList.list) {
            let userTree = getAllJson(treeList.list);
            operationList=getxmselect("#operationCode", "operationCode", userTree);
            salesmanList=getxmselect("#salesmanCode", "salesmanCode", userTree);
        } else {
            operationList= getxmselect("#operationCode", "operationCode", [{name: user.name, value: user.code}])
            salesmanList=getxmselect("#salesmanCode", "salesmanCode", [{name: user.name, value: user.code}])
        }

        //获取当前用户所属部门树()
        let currentDeptTreeList = getAllUserDepartmentTree();
        if (currentDeptTreeList && currentDeptTreeList.list) {
            let deptTree = getAllJson(currentDeptTreeList.list);
            deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
            deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        } else {
            deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
            deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
        }

        //单据信息
        let businessModelName = [
            {name: "正常模式", value: "正常"},
            {name: "备货入库", value: "备货"},
        ];
        businessModelList =getxmselect("#businessModel", "businessModelName", businessModelName);

    });
    form.render();//表单刷新

    let initData = [];
    table.render({
        elem: '#paymentSelect'
        , data: initData
        , toolbar: '#paymentToolbar'
        , totalRow: true
        , cols: [[
            {field: 'numbers',type:'numbers',title:'序号', totalRowText: '合计'}
            , {field: 'purchaseNo', title: '采购单号', sort: true,width: 250}
            , {field: 'supplierName', title: '供应商名称',width: 250}
            , {field: 'createTimeStr', title: '采购日期', sort: true,width: 120}
            , {field: 'salesmanName', title: '业务员', sort: true,width: 120}
            , {field: 'operationName', title: '操作员', sort: true,width: 120}
            , {field: 'saleContractNo', title: '销售合同号', sort: true,width: 120}
            , {field: 'productCode', title: '产品编码', sort: true,width: 120}
            , {field: 'specificationCode', title: '规格编码', sort: true,width: 280}
            , {field: 'amount', title: '采购数量', sort: true,width: 120}
            , {field: 'carryInvoiceNo', title: '出运发票号', sort: true,width: 120}
            , {field: 'businessModelName', title: '业务模式', sort: true,width: 120}
            , {field: 'carryProductNum', title: '出运数量', sort: true,width: 120}
            , {field: 'productUnitPrice', title: '产品成本单价', sort: true,width: 120}
            , {field: 'totalPurchases', title: '采购总额', sort: true, totalRow: true,width: 120}
            , {field: 'totalShipments', title: '出货总额', sort: true, totalRow: true,width: 120}
            , {field: 'pType', title: '产品类型', sort: true,width: 120}
        ]]
        , id: 'maininformationtableid'
        , height: $(document).height() - $('#paymentSelect').offset().top - 75,
        //开启分页
        page: true,
        limits: [300, 600, 900],
    });

    if (purchaseNo!=""){
        $("#contractPurchaseNumber").val(purchaseNo);
        let data={}
        data.contractPurchaseNumber=purchaseNo;
        table.reload('maininformationtableid', {
            page: {
                limit: 300,
                curr: 1
            },
            url: 'payment/paymentShipmentAmountStatisticsByPage',
            where: data
        }, 'data');
        return false;

    }

    //搜索提交
    form.on('submit(submitform)', function (data) {
        table.reload('maininformationtableid', {
            page: {
                limit: 300,
                curr: 1
            },
            url: 'payment/paymentShipmentAmountStatisticsByPage',
            where: data.field
        }, 'data');
        return false;
    });

    form.on('submit(exportData)', function (queryReq) {
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            data: queryReq.field,
            url:"payment/paymentShipmentAmountStatisticsExport",
            success: function(res) {
                if(res.status == 200){
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 100,
                        'X': 100
                    }, 100);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, '出货金额统计.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });
    document.getElementById('clear').onclick = function(){
        operationList.setValue([ ]);
        salesmanList.setValue([ ]);
        businessModelList.setValue([ ]);
        deptSalesmanList.setValue([ ]);
        deptOperationList.setValue([ ]);
    };
});

